/*
 * Copyright 2009 Jesse McLaughlin (nzjess@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.travelfusion.xmlclient.impl.handler;

import static org.travelfusion.xmlclient.util.TfXSPIUtil.findAnnotation;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.travelfusion.xmlclient.handler.Handler;
import org.travelfusion.xmlclient.handler.HandlerPipelineTypeLookup;
import org.travelfusion.xmlclient.handler.HandlerPipelineTypeRegistry;
import org.travelfusion.xmlclient.handler.HandlesRequestsFor;
import org.travelfusion.xmlclient.handler.RequestHandler;
import org.travelfusion.xmlclient.handler.RequestHandlerInterceptedBy;
import org.travelfusion.xmlclient.handler.RequestHandlerInterceptor;
import org.travelfusion.xmlclient.handler.ResponseHandler;
import org.travelfusion.xmlclient.handler.ResponseHandlerInterceptedBy;
import org.travelfusion.xmlclient.handler.ResponseHandlerInterceptor;
import org.travelfusion.xmlclient.xobject.XRequest;
import org.travelfusion.xmlclient.xobject.XResponse;

import com.google.inject.Singleton;

/**
 * Default combined implementation of {@link HandlerPipelineTypeRegistry} and
 * {@link HandlerPipelineTypeLookup}.
 * <p>
 * This class is threadsafe.
 * <p>
 * This implementation automatically registers type associations annotated by {@link RequestHandlerInterceptedBy}
 * and {@link ResponseHandlerInterceptedBy} when the corresponding interceptor type is looked up (if not already
 * registered).
 * <p>
 * This implementation does not allow re-registering of types. An {@link IllegalStateException} will be thrown if
 * two conflicting type registrations are made.
 * 
 * @author Jesse McLaughlin (nzjess@gmail.com)
 */
@Singleton
public class HandlerPipelineTypeRegistryAndLookupImpl implements HandlerPipelineTypeRegistry, HandlerPipelineTypeLookup {

  private final ReadWriteLock requestHandlerTypesLock = new ReentrantReadWriteLock();

  private final Map<Class<? extends XRequest>, Class<? extends RequestHandler<XRequest>>> requestHandlerTypes =
      new HashMap<Class<? extends XRequest>, Class<? extends RequestHandler<XRequest>>>();

  private final ReadWriteLock responseHandlerTypesLock = new ReentrantReadWriteLock();

  private final Map<Class<? extends XRequest>, Class<? extends ResponseHandler<XRequest, XResponse>>> responseHandlerTypes =
      new HashMap<Class<? extends XRequest>, Class<? extends ResponseHandler<XRequest, XResponse>>>();

  private final ReadWriteLock requestHandlerInterceptorTypesLock = new ReentrantReadWriteLock();

  private final Map<Class<? extends RequestHandler<XRequest>>, Class<? extends RequestHandlerInterceptor>> requestHandlerInterceptorTypes =
      new HashMap<Class<? extends RequestHandler<XRequest>>, Class<? extends RequestHandlerInterceptor>>();

  private final ReadWriteLock responseHandlerInterceptorTypesLock = new ReentrantReadWriteLock();

  private final Map<Class<? extends ResponseHandler<XRequest, XResponse>>, Class<? extends ResponseHandlerInterceptor>> responseHandlerInterceptorTypes =
      new HashMap<Class<? extends ResponseHandler<XRequest, XResponse>>, Class<? extends ResponseHandlerInterceptor>>();

  public void registerHandlerType(Class<? extends Handler<?>> handlerType) {
    HandlesRequestsFor handleRequestsFor = handlerType.getAnnotation(HandlesRequestsFor.class);
    if (handleRequestsFor == null)
      throw new IllegalArgumentException("annotation expected on handler class: " + HandlesRequestsFor.class.getName());
    registerHandlerType(handleRequestsFor.value(), handlerType);
  }

  @SuppressWarnings("unchecked")
  public void registerHandlerType(Class<? extends XRequest> requestType, Class<? extends Handler<?>> handlerType) {
    if (RequestHandler.class.isAssignableFrom(handlerType))
      registerRequestHandlerType(requestType, (Class<? extends RequestHandler<XRequest>>)handlerType);
    if (ResponseHandler.class.isAssignableFrom(handlerType))
      registerResponseHandlerType(requestType, (Class<? extends ResponseHandler<XRequest, XResponse>>)handlerType);
  }

  public void registerRequestHandlerType(Class<? extends XRequest> requestType, Class<? extends RequestHandler<XRequest>> handlerType) {
    if (requestType == null) throw new NullPointerException("request type cannot be null");
    if (handlerType == null) throw new NullPointerException("handler type cannot be null");
    requestHandlerTypesLock.writeLock().lock();
    try {
      Class<? extends RequestHandler<XRequest>> registeredType = requestHandlerTypes.get(requestType);
      if (registeredType != null && registeredType != handlerType)
        throw new IllegalStateException("request handler type already registered for: " + requestType.getName() + " ("
            + registeredType.getName() + ")");
      requestHandlerTypes.put(requestType, handlerType);
    }
    finally {
      requestHandlerTypesLock.writeLock().unlock();
    }
  }

  public void registerResponseHandlerType(Class<? extends XRequest> requestType,
      Class<? extends ResponseHandler<XRequest, XResponse>> handlerType) {
    if (requestType == null) throw new NullPointerException("request type cannot be null");
    if (handlerType == null) throw new NullPointerException("handler type cannot be null");
    responseHandlerTypesLock.writeLock().lock();
    try {
      Class<? extends ResponseHandler<XRequest, XResponse>> registeredType = responseHandlerTypes.get(requestType);
      if (registeredType != null && registeredType != handlerType)
        throw new IllegalStateException("response handler type already registered for: " + requestType.getName() + " ("
            + registeredType.getName() + ")");
      responseHandlerTypes.put(requestType, handlerType);
    }
    finally {
      responseHandlerTypesLock.writeLock().unlock();
    }
  }

  public void registerRequestHandlerInterceptorType(Class<? extends RequestHandler<XRequest>> requestHandlerType,
      Class<? extends RequestHandlerInterceptor> interceptorType) {
    if (requestHandlerType == null) throw new NullPointerException("request handler type cannot be null");
    requestHandlerInterceptorTypesLock.writeLock().lock();
    try {
      Class<? extends RequestHandlerInterceptor> registeredType = requestHandlerInterceptorTypes.get(requestHandlerType);
      if (requestHandlerInterceptorTypes.containsKey(requestHandlerType) && registeredType != interceptorType)
        throw new IllegalStateException("request handler interceptor type already registered for: " + requestHandlerType.getName() + " ("
            + ((registeredType != null) ? registeredType.getName() : "null") + ")");
      requestHandlerInterceptorTypes.put(requestHandlerType, interceptorType);
    }
    finally {
      requestHandlerInterceptorTypesLock.writeLock().unlock();
    }
  }

  public void registerResponseHandlerInterceptorType(Class<? extends ResponseHandler<XRequest, XResponse>> responseHandlerType,
      Class<? extends ResponseHandlerInterceptor> interceptorType) {
    if (responseHandlerType == null) throw new NullPointerException("response handler type cannot be null");
    responseHandlerInterceptorTypesLock.writeLock().lock();
    try {
      Class<? extends ResponseHandlerInterceptor> registeredType = responseHandlerInterceptorTypes.get(responseHandlerType);
      if (responseHandlerInterceptorTypes.containsKey(responseHandlerType) && registeredType != interceptorType)
        throw new IllegalStateException("response handler interceptor type already registered for: " + responseHandlerType.getName() + " ("
            + ((registeredType != null) ? registeredType.getName() : "null") + ")");
      responseHandlerInterceptorTypes.put(responseHandlerType, interceptorType);
    }
    finally {
      responseHandlerInterceptorTypesLock.writeLock().unlock();
    }
  }

  public Class<? extends RequestHandler<XRequest>> getRequestHandlerType(Class<? extends XRequest> requestType) {
    requestHandlerTypesLock.readLock().lock();
    try {
      Class<? extends RequestHandler<XRequest>> handlerType = requestHandlerTypes.get(requestType);
      if (handlerType == null) throw new IllegalStateException("no request handler type for: " + requestType.getName());
      return handlerType;
    }
    finally {
      requestHandlerTypesLock.readLock().unlock();
    }
  }

  public Class<? extends ResponseHandler<XRequest, XResponse>> getResponseHandlerType(Class<? extends XRequest> requestType) {
    responseHandlerTypesLock.readLock().lock();
    try {
      Class<? extends ResponseHandler<XRequest, XResponse>> handlerType = responseHandlerTypes.get(requestType);
      if (handlerType == null) throw new IllegalStateException("no response handler type for: " + requestType.getName());
      return handlerType;
    }
    finally {
      responseHandlerTypesLock.readLock().unlock();
    }
  }

  public Class<? extends RequestHandlerInterceptor> getRequestHandlerInterceptorType(
      Class<? extends RequestHandler<XRequest>> requestHandlerType) {
    requestHandlerInterceptorTypesLock.readLock().lock();
    try {
      Class<? extends RequestHandlerInterceptor> interceptorType = requestHandlerInterceptorTypes.get(requestHandlerType);
      if (interceptorType == null && !requestHandlerInterceptorTypes.containsKey(requestHandlerType)) {
        RequestHandlerInterceptedBy requestHandlerInterceptedBy = findAnnotation(requestHandlerType, RequestHandlerInterceptedBy.class);
        if (requestHandlerInterceptedBy != null) {
          interceptorType = requestHandlerInterceptedBy.value();
        }
        requestHandlerInterceptorTypesLock.readLock().unlock();
        try {
          registerRequestHandlerInterceptorType(requestHandlerType, interceptorType);
        }
        finally {
          requestHandlerInterceptorTypesLock.readLock().lock();
        }
      }
      return interceptorType;
    }
    finally {
      requestHandlerInterceptorTypesLock.readLock().unlock();
    }
  }

  public Class<? extends ResponseHandlerInterceptor> getResponseHandlerInterceptorType(
      Class<? extends ResponseHandler<XRequest, XResponse>> responseHandlerType) {
    responseHandlerInterceptorTypesLock.readLock().lock();
    try {
      Class<? extends ResponseHandlerInterceptor> interceptorType = responseHandlerInterceptorTypes.get(responseHandlerType);
      if (interceptorType == null && !responseHandlerInterceptorTypes.containsKey(responseHandlerType)) {
        ResponseHandlerInterceptedBy ResponseHandlerInterceptedBy = findAnnotation(responseHandlerType, ResponseHandlerInterceptedBy.class);
        if (ResponseHandlerInterceptedBy != null) {
          interceptorType = ResponseHandlerInterceptedBy.value();
        }
        responseHandlerInterceptorTypesLock.readLock().unlock();
        try {
          registerResponseHandlerInterceptorType(responseHandlerType, interceptorType);
        }
        finally {
          responseHandlerInterceptorTypesLock.readLock().lock();
        }
      }
      return interceptorType;
    }
    finally {
      responseHandlerInterceptorTypesLock.readLock().unlock();
    }
  }
}
